import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:fluwx/fluwx.dart';
import 'package:get/get.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:sports_new/utils/image_utils.dart';
import 'package:sports_new/utils/widget_utils.dart';
import 'package:weibo_kit/weibo_kit_platform_interface.dart';
import '../../resources/colours.dart';
import '../../utils/utils.dart';
import 'dart:ui' as ui;
import 'dart:developer';

import '../base/qkd_text.dart';

class SharePicSheet extends StatefulWidget {
  const SharePicSheet({super.key, required this.widget});

  final Widget widget;

  @override
  State<SharePicSheet> createState() => _SharePicSheetState();
}

class _SharePicSheetState extends State<SharePicSheet> {
  final GlobalKey imageKey = GlobalKey();
  Fluwx fluwx = Fluwx();
  late WeChatResponseSubscriber _weChatListener;
  List<Function()> tapList = [];
  late Uint8List thumbImage;
  Uint8List? image;
  List images = [
    'save_img.png',
    'share_wx.png',
    'share_timeline.png',
    // 'share_qq.png',
    // 'share_qqzone.png',
    'share_wb.png'
  ];
  List titles = [
    '保存图片',
    '微信',
    '朋友圈',
    // 'QQ',
    // 'QQ空间',
    '微博'];
  bool loading = true;

  @override
  void initState() {
    formData();
    _weChatListener = (res) {
      if (res is WeChatShareResponse) {
        log('state :$res');
      }
    };
    fluwx.addSubscriber(_weChatListener);
    super.initState();
  }

  Future formData() async{
    EasyLoading.addStatusCallback((status) {
      if(status == EasyLoadingStatus.dismiss){
        loading = false;
        update();
      }
    });
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) async{
      await Future.delayed(const Duration(milliseconds: 300));
      EasyLoading.show();
      final boundary = imageKey.currentContext?.findRenderObject();
      if(boundary != null && boundary is RenderRepaintBoundary) {
        double pixelRatio = 1;
        ui.Image pic = await boundary.toImage(pixelRatio: 1);
        ByteData? picBytes = await pic.toByteData(
            format: ui.ImageByteFormat.png);
        log("${picBytes?.lengthInBytes}");
        pixelRatio =
            (1 * 1024 * 1024 ~/ (picBytes?.lengthInBytes ?? 1)).toDouble();
        pic = await boundary.toImage(pixelRatio: pixelRatio / 2);
        picBytes = await pic.toByteData(format: ui.ImageByteFormat.png);
        log("图像大小是${(picBytes?.lengthInBytes ?? 1) / (1024 * 1024)}");
        ByteData bytes = await rootBundle.load(
            Utils.getImgPath('qxb_logo.png'));
        image = picBytes?.buffer.asUint8List();
        thumbImage = bytes.buffer.asUint8List();
        tapList = [
              () {
            try {
              ImageUtils.saveImageToGallery(image: image!);
            } catch (e) {
              log("$e");
            }
          },
              () =>
              Fluwx().share(
                  WeChatShareImageModel(
                      WeChatImage.binary(image!),
                      scene: WeChatScene.session,
                      title: "球客岛",
                      description: "分享给你一张图片"
                  )
              ),
              () =>
              Fluwx().share(
                  WeChatShareImageModel(
                      WeChatImage.binary(image!),
                      scene: WeChatScene.timeline,
                      title: "球客岛",
                      description: "分享给你一张图片"
                  )
              ),
              () =>
              WeiboKitPlatform.instance.shareImage(
                  text: "分享给你一张图片",
                  imageData: image
              ),
        ];
      }
      EasyLoading.dismiss();
      setState(() {});
    });
  }

  @override
  Widget build(BuildContext context) {
    return BottomSheet(
      onClosing: () {  },
        backgroundColor: Colours.transparent,
      builder: (BuildContext context) => Column(
        children: [
          Expanded(
            child: SingleChildScrollView(
              padding: const EdgeInsets.only(top: 20),
              child: Transform.scale(
                scale: loading?0.01:0.9,
                alignment: loading?Alignment.bottomCenter:Alignment.center,
                child: Container(
                  clipBehavior: Clip.antiAlias,
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(8)
                  ),
                  child: RepaintBoundary(
                    key: imageKey,
                    child: widget.widget
                  ),
                ),
              ),
            ),
          ),
          Container(
            color: Colours.greyFD,
            child: Column(
              mainAxisSize: MainAxisSize.min,
              mainAxisAlignment: MainAxisAlignment.end,
              children: [
                const SizedBox(height: 14),
                QkdText(
                  '分享至',
                  color: Colours.grey99
                ),
                const SizedBox(height: 20),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children:
                  List.generate(images.length, (index) => item(index)),
                ),
                const SizedBox(height: 24),
                Container(
                  height: 10,
                  width: double.infinity,
                  color: Colours.greyF7,
                ),
                GestureDetector(
                  behavior: HitTestBehavior.opaque,
                  onTap: () {
                    Get.back();
                  },
                  child: Container(
                    height: 52,
                    color: Colours.greyFD,
                    child: const Center(
                        child: QkdText('取消',
                          fontSize: 17, color: Colours.grey99
                        )
                    ),
                  ),
                ),
              ],
            ),
          )
        ],
      )
    );
  }

  item(int index) {
    return GestureDetector(
      onTap: () {
        Get.back();
        tapList[index].call();
      },
      child: Column(children: [
        Image.asset(Utils.getImgPath(images[index]), width: 50),
        const SizedBox(height: 4),
        QkdText(
          titles[index],
          fontSize: 12, color: Colours.grey99
        )
      ]),
    );
  }

  @override
  void dispose() {
    fluwx.removeSubscriber(_weChatListener);
    super.dispose();
  }
}
